//
//  MenuViewController.m
//  Broker
//
//  Created by ChaoZhou on 16/2/1.
//  Copyright © 2016年 FMM. All rights reserved.
//


#import "MenuViewController.h"
#import "PersonCentreViewController.h"
#import "RentalDemandViewController.h"
#import "FocusedHouseViewController.h"
#import "MainIndexViewController.h"
#import "PressHouseResouceViewController.h"
#import "RoomMateTeamViewController.h"
#import "TravelViewController.h"
#import "DrawerController.h"
#import "SettingsViewController.h"
#import "MessageViewController.h"

#import "MenuTableViewCell.h"

#import "MenuTableTitle.h"

#import "AppDrawer.h"
#import "User.h"
#import "Utility.h"
#import "Constants.h"
#import "ACMacros.h"
#import "HttpServer.h"

#import <SDWebImage/UIImageView+WebCache.h>
#import <SDWebImage/UIButton+WebCache.h>

static const CGFloat drawerDepth = 260.0f;
static NSString * const menuTableViewCellReuseId = @"menuTableViewCellReuseId";

@interface MenuViewController ()<UITableViewDataSource, UITableViewDelegate>
@end

@implementation MenuViewController {
    UINavigationController *nav;
    RentalDemandViewController *rentalDemandVC;
    FocusedHouseViewController *focusedHouseVC;
    PersonCentreViewController *personCentreVC;
    RoomMateTeamViewController *roomMateVC;
    MessageViewController *messageVC;
    SettingsViewController *settingVC;
    MenuTableTitle *menuTableTitle;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self configureNav];
    [self createTableView];
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    MenuViewController *menu = [AppDrawer sharedDrawer].leftViewController;
    [menu reloadHeader];
}

- (void)reloadHeader {
    [menuTableTitle.headerImage sd_setImageWithURL:[NSURL URLWithString:[User sharedUser].avatar]];
    User *user = [User sharedUser];
    [menuTableTitle.nameLabel setText:[User sharedUser].name];
    if ([User sharedUser].certification) {
        [menuTableTitle.checkImage setImage:[UIImage imageNamed:@"check_ID-44-36"]];
    } else {
        [menuTableTitle.checkImage setImage:[UIImage imageNamed:@"check_ID_dim-44-36"]];
    }
    int balance = [[Utility getObjectForKey:kBalance] intValue];
    int trustFee = [[Utility getObjectForKey:kTrusteeFee] intValue];
    [menuTableTitle.balanceLabel setText:[NSString stringWithFormat:@"¥%d",balance - trustFee]];
    self.tableView.tableHeaderView = menuTableTitle;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark - Configuring the view’s layout behavio
- (void)configureNav {
    nav = [AppDrawer sharedDrawer].centerViewController;
}

- (void)createTableView {
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, drawerDepth, self.view.bounds.size.height) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    self.tableView.backgroundView = [[UIImageView alloc]initWithImage:[UIImage new]];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.bounces = false;
    [self.view addSubview:self.tableView];
    [self configureTableViewHeader];
    [self.tableView registerNib:[UINib nibWithNibName:@"MenuTableViewCell" bundle:nil] forCellReuseIdentifier:menuTableViewCellReuseId];
}

- (void)configureTableViewHeader {
    menuTableTitle = [[MenuTableTitle alloc]init];
    menuTableTitle = [[[NSBundle mainBundle] loadNibNamed:@"MenuTableTitle" owner:self options:nil]lastObject];
    menuTableTitle.headerImage.clipsToBounds = true;
    [menuTableTitle.headerImage sd_setImageWithURL:[NSURL URLWithString:[User sharedUser].avatar]];
    User *user = [User sharedUser];
    [menuTableTitle.nameLabel setText:[User sharedUser].name];
    if ([User sharedUser].certification) {
        [menuTableTitle.checkImage setImage:[UIImage imageNamed:@"check_ID-44-36"]];
    } else {
        [menuTableTitle.checkImage setImage:[UIImage imageNamed:@"check_ID_dim-44-36"]];
    }
    int balance = [[Utility getObjectForKey:kBalance] intValue];
    int trustFee = [[Utility getObjectForKey:kTrusteeFee] intValue];
    [menuTableTitle.balanceLabel setText:[NSString stringWithFormat:@"¥%d",balance - trustFee]];
    self.tableView.tableHeaderView = menuTableTitle;
    UITapGestureRecognizer *tapToHomePage = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapToMyHomePage)];
    [self.tableView.tableHeaderView addGestureRecognizer:tapToHomePage];
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (section) {
        case 0:
            return 4;
            break;
        case 1:
            return 2;
            break;
        case 2:
            return 1;
            break;
        case 3:
            return 1;
            break;
   
        default:
            return 0;
            break;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    MenuTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:menuTableViewCellReuseId];
    if(!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor clearColor];
    cell.leftImageView.contentMode = UIViewContentModeScaleAspectFit;
    switch (section) {
        case 0:
            switch (row) {
                case 0:
                    cell.leftImageView.image = [UIImage imageNamed:@"roomie-40"];
                    cell.contentLabel.text = @"室友小组";
                    cell.tagLabel.text = @"加入寝室管理";
                    break;
                case 1:
                    cell.leftImageView.image = [UIImage imageNamed:@"schedule-40-38"];
                    cell.contentLabel.text = @"看房行程";
                    cell.tagLabel.text = @"";
                    break;
                case 2:
                    cell.leftImageView.image = [UIImage imageNamed:@"message-40-34"];
                    cell.contentLabel.text = @"消息中心";
                    cell.tagLabel.text = @"";
                    break;
                case 3:
                    cell.leftImageView.image = [UIImage imageNamed:@"like-40-36"];
                    cell.contentLabel.text = @"关注房源";
                    cell.tagLabel.text = @"";
                    break;
                default:
                    break;
            }
            break;
        case 1:
            switch (row) {
                case 0:
                    cell.leftImageView.image = [UIImage imageNamed:@"publish-40"];
                    cell.contentLabel.text = @"发布房源";
                    cell.tagLabel.text = @"";
                    break;
                case 1:
                    cell.leftImageView.image = [UIImage imageNamed:@"need-40-36"];
                    cell.contentLabel.text = @"租房需求";
                    cell.tagLabel.text = @"";
                    break;
                default:
                    break;
            }
            break;
        case 2:
            cell.leftImageView.image = [UIImage imageNamed:@"set-40-40"];
            cell.contentLabel.text = @"设置";
            cell.tagLabel.text = @"";
            break;
        case 3:

            break;
   
        default:
            break;
    }
    return cell;
}

#pragma mark - Table view delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger section = indexPath.section;
    switch (section) {
        case 3:
            return 0.273 * Main_Screen_Height;
            break;
            
        default:
            return 0.075 * Main_Screen_Height;
            break;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UITableViewHeaderFooterView *headerView = [[UITableViewHeaderFooterView alloc]init];
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(15, 0, drawerDepth - 15, 0.5)];
    [headerView addSubview:line];
    line.backgroundColor = RGBACOLOR(180, 180, 180, 1);
    return headerView;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    switch (section) {
        case 0:
            switch (row) {
                case 0:
                {
                     NSLog(@"1");
                    if (!roomMateVC)
                    {
                        roomMateVC = [[RoomMateTeamViewController alloc]init];
                    }
                    [self pushToController:roomMateVC];
                }
                    break;
                case 1:
                {
                    NSLog(@"2");
                    TravelViewController *traveVC = [[TravelViewController alloc]init];
                    [self pushToController:traveVC];
                }
                    break;
                case 2:
                    NSLog(@"3");
                    if (!messageVC)
                    {
                        messageVC = [[MessageViewController alloc]init];
                    }
                    [self pushToController:messageVC];
                    break;
                case 3:
                {
                    if (!focusedHouseVC) {
                         focusedHouseVC = [[FocusedHouseViewController alloc]init];
                    }
                    [self pushToController:focusedHouseVC];
                }
                    break;
                default:
                    break;
            }
            break;
        case 1:
            switch (row) {
                case 0:
                {
                    PressHouseResouceViewController *pressHouseVC = [[PressHouseResouceViewController alloc]init];
                    [self pushToController:pressHouseVC];
                }
                    break;
                case 1:
                {
                    if (!rentalDemandVC) {
                        rentalDemandVC = [[RentalDemandViewController alloc]init];
                    }
                    [self pushToController:rentalDemandVC];
                }
                    break;
                default:
                    break;
            }
            break;
        case 2:
        {
            if (!settingVC) {
                settingVC = [[SettingsViewController alloc]init];
            }
            [self pushToController:settingVC];
        }
            break;
        case 3:
            break;
            
        default:
            break;
    }
}

- (void)drawerControllerWillOpen:(DrawerController *)drawerController {
    NSLog(@"willOpen");
    [AppDrawer sharedDrawer].isInAction = true;
}

- (void)drawerControllerDidOpen:(DrawerController *)drawerController {
    NSLog(@"didOpen");
    [AppDrawer sharedDrawer].isInAction = false;
    [AppDrawer sharedDrawer].isOpen = true;
}

- (void)drawerControllerWillClose:(DrawerController *)drawerController {
    [AppDrawer sharedDrawer].isInAction = true;
    NSLog(@"willClose");
}

- (void)drawerControllerDidClose:(DrawerController *)drawerController {
    NSLog(@"didClose");
    [AppDrawer sharedDrawer].isInAction = false;
    [AppDrawer sharedDrawer].isOpen = false;
}

#pragma mark - Triggering Methods
- (void)tapToMyHomePage {
    if (!personCentreVC) {
        personCentreVC = [[PersonCentreViewController alloc]initWithNibName:@"PersonCentreViewController" bundle:nil];
    }
    [self pushToController:personCentreVC];
}

- (void)pushToController:(UIViewController *)controller {
    if ([[[AppDrawer sharedDrawer].centerViewController.childViewControllers lastObject]isEqual:controller]) {
        NSLog(@"duplicate");
    } else {
        if ([[AppDrawer sharedDrawer].centerViewController.childViewControllers containsObject:controller]) {
            [nav popToViewController:controller animated:true];
        } else {
            [nav pushViewController:controller animated:true];
        }
        [[AppDrawer sharedDrawer] close];
    }
}

//- (void)loadAds {
//    [HttpServer getAdsWithType:@"index" WithSuccessBlock:^(NSDictionary *successDic) {
//        NSMutableArray *imagesArray = [[NSMutableArray alloc]init];
//        NSMutableArray *urlsArray = [[NSMutableArray alloc]init];
//        for (id item in [successDic objectForKey:@"ads"]) {
//            [imagesArray addObject:[item objectForKey:@"picture"]];
//            [urlsArray addObject:[item objectForKey:@"jumpUrl"]];
//        }
//        [banner refreshBannerWithImageUrls:imagesArray RelatedUrls:urlsArray];
//    } withFailBlock:^(id failData) {
//        NSLog(@"%@",failData);
//    }];
//}

@end
